import db from '../sqlite3db'

const createTableMessage = () => {
  const sql = `
  CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    msgFrom JSON NOT NULL,
    msgTo JSON NOT NULL,
    msgType TEXT NOT NULL,
    message TEXT NOT NULL,
    fileName TEXT,
    filePath TEXT,
    timeStamp INTEGER NOT NULL
  )
`
  db.run(sql, (err) => {
    if (err) {
      console.error(err.message)
    } else {
      console.log('Table messages created successfully')
    }
  })
}

const insertMessage = (insertData) => {
  const sql = `INSERT INTO messages (msgFrom, msgTo, msgType, message, fileName, filePath, timeStamp) VALUES (?,?,?,?,?,?,?)`
  const values = [insertData.msgFrom, insertData.msgTo, insertData.msgType, insertData.message, insertData.fileName, insertData.filePath, insertData.timeStamp]
  db.run(sql, values, (err) => {
    if (err) {
      console.error(err.message)
    } else {
      console.log('Message inserted successfully')
    }
  })
}

const getMessagesByPage = (pageParam) => {
  const sql = `SELECT * FROM messages ORDER BY timeStamp DESC LIMIT ${pageParam.pageSize} OFFSET ${(pageParam.page - 1) * pageParam.pageSize}`
  return new Promise((resolve, reject) => {
    db.all(sql, (err, rows) => {
      if (err) {
        reject(err)
      } else {
        resolve(rows)
      }
    })
  })
}

export {
  createTableMessage,
  insertMessage,
  getMessagesByPage
}